// ol
import VectorLayer from 'ol/layer/Vector';
import { Fill, Stroke, Style, Text, Icon, Circle as CircleStyle } from 'ol/style';
import VectorSource from 'ol/source/Vector';
import GeoJSON from 'ol/format/GeoJSON';
import { Point, LineString, Polygon } from 'ol/geom';
import Draw from 'ol/interaction/Draw'
import { unByKey } from 'ol/Observable';
import Overlay from 'ol/Overlay';
import { Tile as TileLayer } from 'ol/layer';
import { OSM } from 'ol/source';
import { Feature } from 'ol';
import { fromLonLat } from 'ol/proj';
// js
import { transformLonlatToNow, transformNowToLonlat, getCenterPoint, calculateDestination, calculateDistanceAndAzimuth, removeDomByClassName } from "./util.js"

export default {
  // 根据layerName删除图层
  removeLayer: function (map, name) {
    var layerTmp = map.getLayers().getArray().find(m => m.get("name") === name)
    if (layerTmp) map.removeLayer(layerTmp)
  },
  /**
   * 标记绘制 - 图片
   * @param {*} map 
   * @param {*} data 
   * @param {*} config { zIndex, icon, name, scale, featureType }
   */
  drawSign: function (map, data, config) {
    var geojsonObject = {
      type: 'FeatureCollection',
      crs: {
        type: 'name',
      },
      features: []
    };
    for (let item of data) {
      geojsonObject.features.push(
        {
          type: 'Feature',
          geometry: {
            type: "Point",
            coordinates: transformLonlatToNow([item.longitude, item.latitude])
          },
          properties: { ...item, featureType: config.featureType, detail: item }
        }
      )
    }
    const setMapStyle = (feature) => {
      let styleList = []
      const Coordinates = feature.getGeometry().getCoordinates();
      styleList.push(new Style({
        zIndex: config.zIndex || 210,
        image: new Icon({
          src: config.icon,
          scale: config.scale || 0.7
        }),
        geometry: new Point(Coordinates)
      }))
      return styleList
    }
    var source = new VectorSource({
      features: (new GeoJSON()).readFeatures(geojsonObject)
    });
    let layerTmp = map.getLayers().getArray().find(m => m.get("name") === config.name)
    if (layerTmp) map.removeLayer(layerTmp)
    layerTmp = new VectorLayer({
      source: source,
      zIndex: config.zIndex || 210,
      name: config.name,
      style: setMapStyle
    });
    map.addLayer(layerTmp)
  },
  // 纯点
  drawPoint: function (map, data, config) {
    var geojsonObject = {
      type: 'FeatureCollection',
      crs: {
        type: 'name',
      },
      features: []
    };
    for (let item of data) {
      geojsonObject.features.push(
        {
          type: 'Feature',
          geometry: {
            type: "Point",
            coordinates: transformLonlatToNow([item.longitude, item.latitude])
          },
          properties: { ...item, featureType: config.featureType, detail: item }
        }
      )
    }
    const setMapStyle = (feature) => {
      let styleList = []
      const Coordinates = feature.getGeometry().getCoordinates();
      styleList.push(new Style({
        zIndex: config.zIndex || 210,
        image: new CircleStyle({
          radius: 6,
          fill: new Fill({
            color: config.color || "#FFFF66",
          }),
          stroke: new Stroke({
            color: '#fff',
            width: 2,
          }),
        }),
        geometry: new Point(Coordinates)
      }))
      return styleList
    }
    var source = new VectorSource({
      features: (new GeoJSON()).readFeatures(geojsonObject)
    });
    let layerTmp = map.getLayers().getArray().find(m => m.get("name") === config.name)
    if (layerTmp) map.removeLayer(layerTmp)
    layerTmp = new VectorLayer({
      source: source,
      zIndex: config.zIndex || 210,
      name: config.name,
      style: setMapStyle
    });
    map.addLayer(layerTmp)
  },
  /**
   * 绘制水位计
   * @param {*} map 
   * @param {*} data araay
   */
  drawWaterPoint: function (map, data) {
    const className = "water_point_tips"
    removeDomByClassName(className)
    for (let item of data) {
      const containerDom = document.createElement('div');
      containerDom.setAttribute("class", className)
      containerDom.innerHTML = `桥梁净空高度 ${(parseFloat(item.value) - 7 - 1.2 - 2).toFixed(2)}米`;
      let water_tips_dom = new Overlay({
        element: containerDom,
        offset: [35, 35],
        positioning: 'center',
        insertFirst: false
      });
      water_tips_dom.setPosition(transformLonlatToNow([item.longitude, item.latitude]));
      map.addOverlay(water_tips_dom);
    }
  },
  // 区域绘制
  drawArea: function (map, data) {
    var geojsonObject = {
      type: 'FeatureCollection',
      crs: {
        type: 'name',
        properties: {
          name: 'EPSG: 3857'
        }
      },
      features: []
    };

    // 闪烁效果的颜色控制
    const flashStyle = {
      "0": ['rgba(0, 0, 255, 0.6)', 'rgba(0, 0, 0, 0)'],  // 蓝色闪烁
      "1": ['rgba(255, 0, 0, 0.6)', 'rgba(0, 0, 0, 0)'],  // 红色闪烁
      "2": ['rgba(255, 90, 90, 0.6)', 'rgba(255, 90, 90, 0.6)']  // 不闪烁
    };

    // 动态更新的样式函数
    const areaStyleFn = (feature) => {
      let list = [];
      const state = feature.get("state");  // 获取 state 字段
      const flashColors = flashStyle[state];

      if (state === "0" || state === "1") {
        let currentColor = feature.get("flashColor") || flashColors[0];  // 初始颜色

        // 清除现有的定时器（如果有）
        const intervalId = feature.get("intervalId");
        if (intervalId) {
          clearInterval(intervalId);  // 销毁旧的定时器
        }

        // 创建闪烁效果的样式
        list.push(
          new Style({
            fill: new Fill({
              color: currentColor,  // 初始化为蓝色或红色
            }),
          })
        );

        const initFlickerColor = () => {
          // 切换颜色
          currentColor = currentColor === flashColors[0] ? flashColors[1] : flashColors[0];
          feature.set("flashColor", currentColor);  // 更新闪烁颜色

          feature.setStyle(new Style({
            fill: new Fill({
              color: currentColor,  // 更新样式
            }),
            stroke: new Stroke({
              color: "#fff",
              width: 1,
              lineDash: [10, 5]
            }),
          }));
        }

        // 每500ms切换颜色
        const newIntervalId = setInterval(() => {
          initFlickerColor()
        }, 500); // 每500ms切换颜色
        feature.set("intervalId", newIntervalId);  // 存储定时器ID，避免重复创建
        initFlickerColor()

      } else {
        // 不闪烁时的默认颜色
        const color = feature.get("backgroundColor") || 'rgba(255, 90, 90, 0.6)';
        list.push(
          new Style({
            fill: new Fill({
              color,  // 默认颜色
            }),
            stroke: new Stroke({
              color: "#fff",
              width: 1,
              lineDash: [10, 5]
            }),
          })
        );
      }

      // 添加标签等其他样式
      const lonAndLat = feature.values_.bound.coordinates[0].map(m => transformLonlatToNow(m));
      const centerPoint = getCenterPoint(lonAndLat);

      list.push(
        new Style({
          zIndex: 10,
          text: new Text({
            text: feature.values_.name,
            font: '30px sans-serif',
            fill: new Fill({
              color: "rgba(0, 0, 0, 0.5)",
            }),
          }),
          geometry: new Point(centerPoint),
        })
      );

      return list;
    };

    // 遍历数据，构建 geojson
    for (const index in data) {
      let item = data[index];
      item.index = index;
      let list = item.bound.coordinates[0];
      list = list.map(m => transformLonlatToNow(m));

      geojsonObject.features.push(
        {
          type: 'Feature',
          geometry: {
            type: "Polygon",
            coordinates: [list],
          },
          properties: item
        }
      );
    }

    var source = new VectorSource({
      features: (new GeoJSON()).readFeatures(geojsonObject)
    });

    let layerTmp = map.getLayers().getArray().find(m => m.get("name") === "Area");
    if (layerTmp) map.removeLayer(layerTmp);

    layerTmp = new VectorLayer({
      source: source,
      zIndex: 201,
      name: "Area",
      style: areaStyleFn
    });
    map.addLayer(layerTmp);
  },
  /**
   * 轨迹绘制
   * @param {*} map 
   * @param {*} list 
   * @param {*} layerName tarvel_{targetId}
   */
  drawTravel: function (map, list, layerName, color = '#FFFF66b3', zindex = 219) {
    var geojsonObject = {
      type: 'FeatureCollection',
      features: []
    };
    // 绘制航线
    let lineList = [];
    for (let index in list) {
      let item = list[index]
      const p = [parseFloat(item.longitude), parseFloat(item.latitude)]
      lineList.push(transformLonlatToNow(p))
    }
    geojsonObject.features.push(
      {
        type: 'Feature',
        geometry: {
          type: "LineString",
          coordinates: lineList
        },
      }
    )
    var source = new VectorSource({
      features: []
    });
    var GJson = (new GeoJSON()).readFeatures(geojsonObject)
    for (let index in GJson) {
      source.addFeature(GJson[index])
    }
    var layerTmp = map.getLayers().getArray().find(m => m.get("name") === layerName)
    if (layerTmp) map.removeLayer(layerTmp)
    layerTmp = new VectorLayer({
      source: source,
      zIndex: zindex,
      name: layerName,
      style: new Style({
        stroke: new Stroke({
          color: color,
          width: 3,
        }),
      })
    });
    map.addLayer(layerTmp);
  },
  /**
   * 报警详情里面绘制点迹，最后一个点巨大化，因为时间倒序
   */
  drawPointsTravel: function (map, list, layerName) {
    var geojsonObject = {
      type: 'FeatureCollection',
      features: []
    };
    const style = (feature) => {
      const type = feature.get("pointType")
      if (type === "line") {
        return new Style({
          stroke: new Stroke({
            // color: '#F0188B',
            color: "#FFFF66",
            width: 3,
          }),
        })
      } else {
        const row = feature.get("detail")
        const heading = row[2];
        let src, rotation;
        if (!heading) {
          src = '/images/sign/ship_cir.png'
          rotation = 0
        } else {
          src = '/images/sign/ship_stop.png'
          rotation = Math.PI / (180 / heading)
        }
        return new Style({
          image: new Icon({
            src,
            scale: 1,
            rotation,
            color: "#FFFF66"
          }),
        })
        // return new Style({
        //   image: new CircleStyle({
        //     radius: 6,
        //     fill: new Fill({
        //       // color: '#F0188B',
        //       color: "#FFFF66",
        //     }),
        //     stroke: new Stroke({
        //       color: '#fff',
        //       width: 2,
        //     }),
        //   }),
        // });
      }
    }
    // 绘制航线
    let lineList = [];
    for (let item of list) {
      lineList.push(transformLonlatToNow(item))
    }
    geojsonObject.features.push(
      {
        type: 'Feature',
        geometry: {
          type: "LineString",
          coordinates: lineList
        },
        properties: { pointType: "line" }
      }
    )
    geojsonObject.features.push(
      {
        type: 'Feature',
        geometry: {
          type: "Point",
          coordinates: transformLonlatToNow(list[list.length - 1])
        },
        properties: Object.assign({ pointType: "ship", detail: list[list.length - 1] })
      }
    )
    var source = new VectorSource({
      features: []
    });
    var GJson = (new GeoJSON()).readFeatures(geojsonObject)
    for (let index in GJson) {
      source.addFeature(GJson[index])
    }
    var layerTmp = map.getLayers().getArray().find(m => m.get("name") === layerName)
    if (layerTmp) map.removeLayer(layerTmp)
    layerTmp = new VectorLayer({
      source: source,
      zIndex: 219,
      name: layerName,
      style: style
    });
    map.addLayer(layerTmp);
  },
  /**
   * 手动测绘
   * @param {*} map 
   * @param {*} measureType  Polygon LineString
   */
  measure: function (map, measureType) {
    return new Promise((r) => {
      // 绘制图形样式
      const drawStyle = () => {
        return new Style({
          fill: new Fill({
            color: 'rgba(100, 205, 142, 0.5)'
          }),
          stroke: new Stroke({
            color: 'rgba(0, 0, 0, 0.5)',
            width: 2
          }),
          image: new CircleStyle({
            radius: 3,
            stroke: new Stroke({
              color: 'rgba(0, 0, 0, 0.7)'
            }),
            fill: new Fill({
              color: 'rgba(255, 255, 255, 0.2)'
            })
          })
        })
      }
      // 测绘图形中点的样式
      function drawStyleFn(feature) {
        let styleList = [drawStyle()]
        const coordinatesType = feature.getGeometry().getType();
        if (coordinatesType === "Circle") return styleList
        const Coordinates = feature.getGeometry().getCoordinates();
        let list = coordinatesType === "Polygon" ? Coordinates[0] : Coordinates;
        const colors = ["#88FF88", "#FFFFFF", "#D53645"];
        var fn = (row, index = 1) => {
          styleList.push(
            new Style({
              zIndex: 10,
              image: new CircleStyle({
                radius: 3.5,
                fill: new Fill({
                  color: colors[index],
                }),
                stroke: new Stroke({
                  color: "#333333",
                  width: 1.5,
                }),
              }),
              geometry: new Point(row),
            })
          );
        };
        if (coordinatesType === "Polygon") {
          list = list.slice(0, list.length - 1);
        }
        for (let item of list.slice(1, list.length - 1)) {
          fn(item, 1);
        }
        fn(list[0], 0);
        fn(list[list.length - 1], 2);
        return styleList;
      }
      // 绘制时的样式
      const measureStyle = () => {
        return new Style({
          fill: new Fill({
            color: 'rgba(255, 255, 255, 0.2)'
          }),
          stroke: new Stroke({
            color: 'rgba(20, 172, 121, 0.5)',
            lineDash: [10, 10],
            width: 2
          }),
          image: new CircleStyle({
            radius: 3,
            stroke: new Stroke({
              color: 'rgba(0, 0, 0, 0.7)'
            }),
            fill: new Fill({
              color: 'rgba(255, 255, 255, 0.2)'
            })
          })
        })
      }
      // 创建一个当前要绘制的对象
      var sketch;
      // 创建一个帮助提示框对象
      var helpTooltipElement;
      // 创建一个帮助提示信息对象
      var helpTooltip;
      // 创建一个测量提示框对象
      var measureTooltipElement;
      // 创建一个测量提示信息对象
      var measureTooltip;
      // 继续绘制多边形的提示信息
      var continuePolygonMsg = '双击结束绘制';
      // 继续绘制线段的提示信息
      var continueLineMsg = '双击结束绘制';
      // 创建两个提示框实例
      createHelpTooltip();

      // 绑定鼠标事件
      var pointerMoveHandler = function (evt) {
        if (evt.dragging) {
          return;
        }
        /** @type {string} */
        var helpMsg = '请点击开始绘制';

        if (sketch) {
          var geom = (sketch.getGeometry());
          if (geom instanceof Polygon) {
            helpMsg = continuePolygonMsg;
          } else if (geom instanceof LineString) {
            helpMsg = continueLineMsg;
          }
        }
        helpTooltipElement.innerHTML = helpMsg;
        helpTooltip.setPosition(evt.coordinate);
        helpTooltipElement.classList.remove('hidden');
      };

      // 添加鼠标事件
      map.on('pointermove', pointerMoveHandler);
      map.getViewport().addEventListener('mouseout', function () {
        helpTooltipElement.classList.add('hidden');
      });

      var draw;
      var source;
      var layerTmp = map.getLayers().getArray().find(m => m.get("name") === "measureLayer")
      if (!layerTmp) {
        layerTmp = new VectorLayer({
          source: new VectorSource({
            features: [],
          }),
          zIndex: 230,
          name: "measureLayer",
          style: drawStyleFn
        });
        map.addLayer(layerTmp)
      }
      source = layerTmp.getSource();

      // 图形样式
      draw = new Draw({
        source: source,
        type: measureType,
        style: measureStyle
      })

      function addInteraction() {
        map.addInteraction(draw);

        var listener;
        var type;
        draw.on('drawstart',
          function (evt) {
            // set sketch
            sketch = evt.feature;

            /** @type {module:ol/coordinate~Coordinate|undefined} */
            var tooltipCoord = evt.coordinate;

            listener = sketch.getGeometry().on('change', function (evt) {
              var geom = evt.target;
              if (geom instanceof Polygon) {
                tooltipCoord = geom.getInteriorPoint().getCoordinates();
                type = "Polygon"
              } else if (geom instanceof LineString) {
                tooltipCoord = geom.getLastCoordinate();
                type = "LineString"
              }
            });
          }, this);

        draw.on('drawend',
          function (e) {
            sketch = null;
            // 移除事件监听
            unByKey(listener);
            map.un('pointermove', pointerMoveHandler);
            // 获取坐标点
            const geometry = e.feature.getGeometry()
            let corrdinates = geometry.getCoordinates()
            // 移除地图单击事件
            map.removeInteraction(draw);
            map.removeOverlay(helpTooltip);
            // Polygon LineString
            if (measureType === 'Polygon') {
              r(corrdinates[0].map(m => transformNowToLonlat(m)))
            } else {
              r(corrdinates.map(m => transformNowToLonlat(m)))
            }
          }, this);
      }

      // 将帮助提示语添加到图层中
      function createHelpTooltip() {
        if (helpTooltipElement) {
          helpTooltipElement.parentNode.removeChild(helpTooltipElement);
        }
        helpTooltipElement = document.createElement('div');
        helpTooltipElement.className = 'tooltip hidden';
        helpTooltip = new Overlay({
          element: helpTooltipElement,
          offset: [15, 0],
          positioning: 'center-left'
        });
        map.addOverlay(helpTooltip);
      }
      // 量测调用
      addInteraction();
    })
  },
  drawRadar: function (map, data, config) {
    // 计算目的地经纬度
    function calculateDestination(lat0, lon0, bearing, distance) {
      const R = 6371000; // 地球半径，单位米
      const toRadians = Math.PI / 180; // 角度转弧度因子
      const toDegrees = 180 / Math.PI; // 弧度转角度因子

      // 将原点的经纬度转换为弧度
      lat0 = lat0 * toRadians;
      lon0 = lon0 * toRadians;

      // 将目标与正北的夹角转换为弧度
      bearing = bearing * toRadians;

      // 计算纬度的变化
      const deltaLat = distance / R * Math.cos(bearing);

      // 计算经度的变化
      const deltaLon = distance / (R * Math.cos(lat0)) * Math.sin(bearing);

      // 计算目标点的经纬度
      const lat1 = lat0 + deltaLat;
      const lon1 = lon0 + deltaLon;

      // 将结果转换回度数
      return {
        lat: lat1 * toDegrees,
        lon: lon1 * toDegrees
      };
    }

    // 生成半圆的坐标点
    function generateHalfCircle(center, radius, startAngle, endAngle, numPoints) {
      const coords = [];
      for (let i = 0; i <= numPoints; i++) {
        const angle = startAngle + (i / numPoints) * (endAngle - startAngle);
        const destination = calculateDestination(center[1], center[0], angle, radius);
        coords.push(fromLonLat([destination.lon, destination.lat]));
      }
      // 闭合半圆
      coords.push(fromLonLat([center[0], center[1]]));
      return coords;
    }

    function getAngle(num) {
      // return (num + 360) % 360;
      return num
    }

    function getHalfCircle(row) {
      // 设置半圆的参数
      const center = [row.longitude, row.latitude]; // 原点经纬度
      const radius = row.maxDistance;
      const startAngle = getAngle(row.northAngle - (row.fieldOfView / 2));
      const endAngle = getAngle(row.northAngle + (row.fieldOfView / 2));
      const numPoints = 50; // 圆弧的点数
      // 创建半圆
      const halfCircleCoords = generateHalfCircle(center, radius, startAngle, endAngle, numPoints);
      return new Polygon([halfCircleCoords]);
    }

    function setHalfStyle(featrue) {
      const detail = featrue.get('detail');
      return new Style({
        fill: new Fill({
          color: detail.backgroundColor,
        }),
        stroke: new Stroke({
          color: 'rgba(255, 100, 50, 1)',
          width: 0.1,
        }),
      });
    }

    // 生成弧线的坐标点
    function generateArc(center, radius, startAngle, endAngle, numPoints) {
      const coords = [];
      for (let i = 0; i <= numPoints; i++) {
        const angle = startAngle + (i / numPoints) * (endAngle - startAngle);
        const destination = calculateDestination(center[1], center[0], angle, radius);
        coords.push(fromLonLat([destination.lon, destination.lat]));
      }
      return coords;
    }

    // 生成弧线的 Feature
    const setArcStyle = (feature) => {
      const label = feature.get('label');
      return new Style({
        stroke: new Stroke({
          color: 'rgba(255, 255, 255, 0.8)',
          width: 1,
        }),
        text: new Text({
          text: label,
          font: '12px Arial',
          fill: new Fill({
            color: '#fff',
          }),
          offsetY: 0,
          placement: 'point',
        }),
      });
    };

    function createArcFeature(row, radius, startAngle, endAngle) {
      const center = [row.longitude, row.latitude]; // 原点经纬度
      const numPoints = row.fieldOfView; // 弧线的平滑度
      const arcCoords = generateArc(center, radius, startAngle, endAngle, numPoints);
      const arcFeature = new Feature({
        geometry: new LineString(arcCoords),
        label: radius + '', // 弧线的标注
        radius: radius, // 用于标注位置的半径
        type: "arc",
        detail: row
      });
      return arcFeature;
    }

    function getArcFeature(row) {
      const startAngle = getAngle(row.northAngle - (row.fieldOfView / 2)); // -15 度
      const endAngle = getAngle(row.northAngle + (row.fieldOfView / 2)); // 15 度
      const maxRadius = row.maxDistance; // 最大半径
      const features = [];
      for (let i = row.distanceScale; i <= maxRadius; i += row.distanceScale) {
        const arcFeature = createArcFeature(row, i, startAngle, endAngle);
        features.push(arcFeature);
      }
      return features;
    }

    // 创建图层和样式
    let FeatureList = [];
    for (let item of data) {
      FeatureList.push(new Feature({
        geometry: getHalfCircle(item),
        detail: item,
        type: "half"
      }));
      FeatureList = FeatureList.concat(getArcFeature(item));
    }

    function styleFunction(feature) {
      const type = feature.get('type');
      if (type === "half") {
        return setHalfStyle(feature);
      } else {
        return setArcStyle(feature);
      }
    }

    const vectorSource = new VectorSource({
      features: FeatureList,
    });

    let layerTmp = map.getLayers().getArray().find(m => m.get("name") === config.name);
    if (layerTmp) map.removeLayer(layerTmp);
    layerTmp = new VectorLayer({
      source: vectorSource,
      style: styleFunction,
      zIndex: config.zIndex || 210,
      name: config.name,
    });

    // 添加图层到地图
    map.addLayer(layerTmp);
  },
  cameraRange: function (map, data, layerName) {
    // 计算目的地经纬度
    function calculateDestination(lat0, lon0, bearing, distance) {
      const R = 6371000; // 地球半径，单位米
      const toRadians = Math.PI / 180; // 角度转弧度因子
      const toDegrees = 180 / Math.PI; // 弧度转角度因子

      // 将原点的经纬度转换为弧度
      lat0 = lat0 * toRadians;
      lon0 = lon0 * toRadians;

      // 将目标与正北的夹角转换为弧度
      bearing = bearing * toRadians;

      // 计算纬度的变化
      const deltaLat = distance / R * Math.cos(bearing);

      // 计算经度的变化
      const deltaLon = distance / (R * Math.cos(lat0)) * Math.sin(bearing);

      // 计算目标点的经纬度
      const lat1 = lat0 + deltaLat;
      const lon1 = lon0 + deltaLon;

      // 将结果转换回度数
      return {
        lat: lat1 * toDegrees,
        lon: lon1 * toDegrees
      };
    }

    // 生成半圆的坐标点
    function generateHalfCircle(center, radius, startAngle, endAngle, numPoints) {
      const coords = [];
      for (let i = 0; i <= numPoints; i++) {
        const angle = startAngle + (i / numPoints) * (endAngle - startAngle);
        const destination = calculateDestination(center[1], center[0], angle, radius);
        coords.push(fromLonLat([destination.lon, destination.lat]));
      }
      // 闭合半圆
      coords.push(fromLonLat([center[0], center[1]]));
      return coords;
    }

    function getAngle(num) {
      // return (num + 360) % 360;
      return num
    }

    function getHalfCircle(row) {
      // 设置半圆的参数
      const center = [row.cameraLongitude, row.cameraLatitude]; // 原点经纬度
      const { distance, azimuth } = calculateDistanceAndAzimuth([row.cameraLongitude, row.cameraLatitude], [row.pointLongitude, row.pointLatitude])
      const radius = distance
      const fieldOfView = 6; // 范围
      const startAngle = getAngle(azimuth - (fieldOfView / 2));
      const endAngle = getAngle(azimuth + (fieldOfView / 2));
      const numPoints = 50; // 圆弧的点数
      // 创建半圆
      const halfCircleCoords = generateHalfCircle(center, radius, startAngle, endAngle, numPoints);
      return new Polygon([halfCircleCoords]);
    }

    function setHalfStyle(featrue) {
      const detail = featrue.get('detail');
      return new Style({
        fill: new Fill({
          color: "rgba(255, 255, 255, 0.2)",
        }),
        stroke: new Stroke({
          color: 'rgba(255, 100, 50, 1)',
          width: 0.1,
        }),
      });
    }

    // 创建图层和样式
    let FeatureList = [];
    FeatureList.push(new Feature({
      geometry: getHalfCircle(data),
      detail: data,
      type: "half"
    }));

    function styleFunction(feature) {
      const type = feature.get('type');
      if (type === "half") {
        return setHalfStyle(feature);
      }
    }

    const vectorSource = new VectorSource({
      features: FeatureList,
    });

    let layerTmp = map.getLayers().getArray().find(m => m.get("name") === `cameraRange_${layerName}`);
    if (layerTmp) map.removeLayer(layerTmp);
    layerTmp = new VectorLayer({
      source: vectorSource,
      style: styleFunction,
      zIndex: 300,
      name: `cameraRange_${layerName}`,
    });

    // 添加图层到地图
    map.addLayer(layerTmp);
  },
  removeCameraRange: function (map, layerName) {
    let layerTmp = map.getLayers().getArray().find(m => m.get("name") === `cameraRange_${layerName}`);
    if (layerTmp) map.removeLayer(layerTmp);
  },
  drawBridgeList: function (map, features) {
    const textStyle = new Style({
      text: new Text({
        font: '20px Arial',
        fill: new Fill({ color: '#333' }),
        stroke: new Stroke({
          color: 'white',
          width: 3
        }),
        text: '',
        textAlign: 'left'
      })
    });

    const vectorSource = new VectorSource();

    features.forEach(item => {
      const feature = new Feature({
        geometry: new Point(fromLonLat([item.longitude, item.latitude])),
      });
      textStyle.getText().setText(item.bridgeName);
      feature.setStyle(textStyle);
      vectorSource.addFeature(feature);
    });

    const vectorLayer = new VectorLayer({
      source: vectorSource,
      zIndex: 210
    });

    map.addLayer(vectorLayer);
  }
}